﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using cludg.Infrastructure.Core.Logging;
using cludg.Web.Core.Filters;
using cludg.Infrastructure.Core.Attributes;
using cludg.Web.Core.Modules;


namespace cludg.Web.Core.ViewEngines
{
	public class ViewEngineUtil
	{
		[Dependency]
		public IEnumerable<IViewEngineProvider> ViewEngineProviders { get; set; }
		[Dependency]
		public ILogger Logger { get; set; }
		[Dependency]
		public IModuleManager ModuleManager { get; set; }

		public void UpdateViewLocations(ViewEngineCollection collection)
		{
			var modules = ModuleManager.RegisteredModules();
			var locations = modules.Select(x => Path.Combine("~/Modules", x.ModuleName));

			var moduleViewEngines = ViewEngineProviders
				.Select(x => x.CreateModulesViewEngine(new CreateModulesViewEngineParams { VirtualPaths = locations }));
			Logger.DebugFormat("Module locations:\r\n\t-{0}", string.Join("\r\n\t-", locations.ToArray()));

			var requestViewEngines = new ViewEngineCollection(
					moduleViewEngines.ToArray());

			foreach (var engine in requestViewEngines)
				collection.Add(engine);
		}
	}
}
